import { useState } from "react";

interface State<D> {
  error: Error | null;
  data: D | null;
  status: "idle" | "loading" | "success" | "error";
}

// 设置默认状态
const defaultInitialState: State<null> = {
  status: "idle",
  error: null,
  data: null,
};
export const useAsync = <D>(initialState?: State<D>) => {
  // 初始化数据
  const [state, setState] = useState<State<D>>({
    ...initialState,
    ...defaultInitialState,
  });
  // 调用setData说明请求成功
  const setData = (data: D) => {
    setState({
      status: "success",
      error: null,
      data,
    });
  };
  // 调用setError说明请求失败
  const setError = (error: Error) => {
    setState({
      status: "error",
      error,
      data: null,
    });
  };
  // 调用run，进行异步请求数据
  const run = (promise: Promise<D>) => {
    // 没有传入Promise对象或者Promise对象为空
    if (!promise || !promise.then()) {
      throw new Error("请传入 Promise类型 数据"); // throw 会停止后面所有执行
    }
    // 传入Promise
    setState({ ...state, status: "loading" });
    return promise
      .then((data) => {
        setData(data);
        return data;
      })
      .catch((error) => {
        setError(error);
        return error;
      });
  };
  // customize-hook传递出去的数据
  return {
    isIdle: state.status === "idle",
    isLoading: state.status === "loading",
    isSuccess: state.status === "success",
    isError: state.status === "error",
    run,
    setData,
    setError,
    ...state,
  };
};
